<?php

namespace app\admin\controller\item;

use app\admin\model\ItemSku;
use app\common\controller\Backend;
use app\admin\model\inventory\Lists;
use think\Db;
use TCPDF;


class Item extends Backend
{
    

    protected $model = null;
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Item;

    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->aid;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    //事物开启
                    Db::startTrans();
                    $result = $this->model->allowField(true)->insertGetId($params);
                    $id =  $this->model->getLastInsID();
                    if(!empty($id) && $result !== false){
                        $inventory = new Lists();
                        $data[$this->dataLimitField] = $this->auth->aid;
                        $data['itemid'] = $id;
                        $data['itemname'] = $params['itemname'];
                        $data['sku'] = $params['sku'];

                        $rsInv = $inventory->save($data);
                        if($rsInv !== false){
                            Db::commit();
                            $this->success();
                        }else{
                            Db::rollback();
                            $this->error('添加失败，请重试');
                        }
                    }else{
                        $this->error($this->model->getError());
                    }
                    //同步至库存一览

//                    if(!empty($id) && $result !== false){
//                        //批量插入
//                        $itemSku = model('ItemSku');
//                        $data['itemid'] = $id;
//                        $data['sku'] = $params['sku'];
//                        $data['isku'] = $params['isku'];
//                        $data['itemsource'] = $params['sitemsourceku'];
//                        $rsSku = $itemSku->save($data);
//                    }

                   // if ($result !== false && $rsSku !== false) {
//                    if ($result !== false) {
//                        Db::commit();
//                        $this->success();
//                    } else {
//                        Db::rollback();
//                        $this->error($this->model->getError());
//                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    //编辑时才 关联平台SKU
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    Db::startTrans();
                    $result = $row->allowField(true)->save($params);

                    $itemSku = new ItemSku;
                    $itemSku->where('itemid','=',$ids)->delete();

                    if (isset($params['rsku'])) {
                        for ($i = 0; $i < count($params['rsku']); $i++) {
                            $data = array();
                            $data['sku'] = $params['rsku'][$i];
                            $data['name'] = $params['name'][$i];
                            $data['itemsource'] = $params['itemsource'][$i];
                            $data['isku'] = $row['sku'];
                            $data['itemid'] = $ids;

                            $rsItem = $itemSku->insert($data);
                            if ($rsItem === false) {
                                Db::rollback();
                                $this->error('保存失败，请重试');
                            }
                        }
                    }

                    if ($result !== false) {
                        Db::commit();
                        $this->success('修改成功！');
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //取出关联SKU产品
        $itemSku = new ItemSku;
        $iSkus = $itemSku->where('itemid','=',$ids)->select();
        $itemSkus = collection($iSkus)->toArray();

        $this->view->assign("skus", $itemSkus);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function printItem(){
        $ids =  $this->request->get("ids");
        $info = $this->model->get($ids)->toArray();

        $this->toPdf($info);
    }

    public function toPdf($data){

        $pdf = new TCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT, array(100,100), true, 'UTF-8', false);

        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle('TCPDF Example 002');
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->SetFont('times', 'BI', 10);
        $pdf->AddPage();

        $style = array(
            'position' => '',
            'align' => 'C',
            'stretch' => false,
            'fitwidth' => true,
            'cellfitalign' => '',
            'border' => false,
            'hpadding' => 'auto',
            'vpadding' => 'auto',
            'fgcolor' => array(0,0,0),
            'bgcolor' => false,
            'text' => true,
            'font' => 'helvetica',
            'fontsize' => 8,
            'stretchtext' => 4
        );
        $style['position'] = 'C';
        $pdf->write1DBarcode($data['sku'], 'C39', '', '', '', 25, 0.4, $style, 'N');
        $pdf->Write(0, $data['itemname'], '', 0, 'C', true, 0, false, false, 0);

        $Inbound = $data['sku'];

        $pdf->lastPage();
        $pdf->Output($Inbound.'.pdf', 'D');
    }


}
